<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <form action="">
    用户名：<input type="text" id="txt" name="username"><span id="msg"></span><br>
    密  码：<input type="text" name="userpwd"><br>
    <input type="submit" value="注册">
  </form>
  <script src="xhr.js"></script>
  <script>
    //1.用户名文本框注册失焦事件
    document.getElementById('txt').onblur = function(){
      //2.失焦事件：
      // 1)获取已填写好的用户名
      var username = this.value;
      // 2)发送 Ajax 请求并将用户名一起发送给后端
      //  ①实例化 xhr 对象
      var xhr =  getXhr();
      //  ② 调用open方法准备请求
      xhr.open('get','/api/checkUser?username=' + username);
      //  ③ 调用send方法发送请求
      xhr.send();
      //  3)接收后端返回的结果
      xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
          if(xhr.responseText == '用户名可用'){
            document.getElementById('msg').style.color = 'green';
          }else{
            document.getElementById('msg').style.color = 'red';
          }
          // alert(xhr.responseText)
          document.getElementById('msg').innerHTML = xhr.responseText;
        }
      }
    }
  </script>
</body>
</html>